import 'package:pacsun/components/appbar.dart';
import 'package:pacsun/constants/constant.dart';
import 'package:pacsun/utils/PreferenceUtils.dart';
import 'package:pacsun/view/create/become/index.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// ------------------------------------------------------------------------------------- //
import 'package:pacsun/provider/userProv.dart' show UserProvider;

// ------------------------------------------------------------------------------------- //
import 'package:pacsun/view/task/theme/app_colors.dart';
import '../create/welcome_page.dart';
import './registePage.dart' show RegisterPage;

// ------------------------------------------------------------------------------------- //
import '../../provider/termsProv.dart' show TermsProvider;

// ------------------------------------------------------------------------------------- //
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: CommonTransparentAppBar(),
        backgroundColor: Colors.black,
        body: Container(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: LoginFormWidget()),
      );
}

class LoginFormWidget extends StatefulWidget {
  const LoginFormWidget({super.key});

  @override
  State<LoginFormWidget> createState() => _LoginFormWidgetState();
}

class _LoginFormWidgetState extends State<LoginFormWidget> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _passwordFocusNode = FocusNode();
  final _submitFocusNode = FocusNode();

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _passwordFocusNode.dispose();
    _submitFocusNode.dispose();
    super.dispose();
  }

  Future<void> _handleLogin(BuildContext context) async {
    if (_formKey.currentState!.validate()) {
      final userProvider = Provider.of<UserProvider>(context, listen: false);

      // Login requset
      await userProvider.login(
          _usernameController.text.trim(), _passwordController.text.trim(), context);

      // Fetching user data
      await userProvider.getUserInfo(userProvider.currentUser!.id!, context);
      await PreferenceUtils.setBool(Constant.SP_KEY_GUIDE_EXECUTED, false);
      // 登录成功后跳转到Create页面
      if (userProvider.currentUser != null) {
        if (userProvider.isCreate) {
          Navigator.of(context).pop(); // 关闭登录页面
        } else {
          Navigator.of(context).replace(
            oldRoute: ModalRoute.of(context)!,
            newRoute: MaterialPageRoute(builder: (context) => BeComePage()),
          );
        }

        // 跳转到Create页面 - 需要通过回调或者其他方式通知主页面切换到Create tab
        // 由于我们使用的是IndexedStack，需要通过回调来切换页面
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 95.h),
              Text('Sign In', style: customTextStyle(fontSize: 35, fontWeight: 900)),
              SizedBox(height: 35.h),
              const Text('Email address',
                  style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'Poppins',
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      letterSpacing: 0)),
              SizedBox(height: 12.h),
              UserInputField(
                  controller: _usernameController,
                  currentNode: null,
                  targetNode: _passwordFocusNode,
                  validator: (value) => value?.isEmpty ?? true ? 'Email required' : null),
              SizedBox(height: 12.h),
              const Text('Password',
                  style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'Poppins',
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      letterSpacing: 0)),
              PasswordInputField(
                controller: _passwordController,
                currentNode: _passwordFocusNode,
                targetNode: _submitFocusNode,
                validator: (value) => value?.isEmpty ?? true ? 'Password required' : null,
              ),
              SizedBox(height: 35.h),
              LoginButton(onPressed: () => _handleLogin(context)),
              SizedBox(height: 12.h),
              const TermsCheckWidget(),
              SizedBox(height: 50.h),
              InkWell(
                onTap: () => Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => const RegisterPage()),
                ),
                child: Center(
                  child: Text.rich(
                    style: customTextStyle(fontSize: 14, opacity: 0.5),
                    TextSpan(
                      style: TextStyle(fontWeight: FontWeight.bold),
                      children: [
                        TextSpan(text: "Don't Have An Account Yet? "),
                        TextSpan(
                            text: 'Register', style: customTextStyle(fontSize: 16, fontWeight: 600))
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class UserInputField extends StatelessWidget {
  final TextEditingController controller;
  final FocusNode? currentNode;
  final FocusNode? targetNode;
  final String? Function(String?)? validator;

  const UserInputField({
    super.key,
    required this.controller,
    this.currentNode,
    this.targetNode,
    this.validator,
  });

  @override
  Widget build(BuildContext context) => TextFormField(
        controller: controller,
        focusNode: currentNode,
        style: customTextStyle(fontSize: 14),
        cursorColor: AppColors.white,
        decoration: customInputDecoration(),
        validator: validator,
        onFieldSubmitted: (_) => FocusScope.of(context).requestFocus(targetNode),
      );
}

class PasswordInputField extends StatefulWidget {
  final TextEditingController controller;
  final FocusNode? currentNode;
  final FocusNode? targetNode;
  final String? Function(String?)? validator;

  const PasswordInputField({
    super.key,
    required this.controller,
    this.currentNode,
    this.targetNode,
    this.validator,
  });

  @override
  State<PasswordInputField> createState() => _PasswordInputFieldState();
}

class _PasswordInputFieldState extends State<PasswordInputField> {
  bool _pwVisibleToggle = true;

  @override
  Widget build(BuildContext context) => TextFormField(
        controller: widget.controller,
        obscureText: _pwVisibleToggle,
        focusNode: widget.currentNode,
        cursorColor: AppColors.white,
        style: customTextStyle(fontSize: 14),
        validator: widget.validator,
        onFieldSubmitted: (_) => FocusScope.of(context).requestFocus(widget.targetNode),
        decoration: InputDecoration(
          fillColor: AppColors.containerBg,
          hintStyle: TextStyle(color: Colors.white),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
            borderSide: BorderSide(
              color: Colors.white,
              width: 2.0,
            ),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
            borderSide: BorderSide(
              color: AppColors.white,
              width: 1.r,
            ),
          ),
          suffixIcon: Tooltip(
            message: _pwVisibleToggle ? "Show password" : "Hide password",
            child: InkWell(
              onTap: () => setState(() => _pwVisibleToggle = !_pwVisibleToggle),
              child: Icon(_pwVisibleToggle ? Icons.visibility : Icons.visibility_off),
            ),
          ),
          suffixIconColor: AppColors.white.withAlpha(128),
        ),
      );
}

class TermsCheckWidget extends StatelessWidget {
  const TermsCheckWidget({super.key});

  // void showTermsDialog(BuildContext context) {
  //   final screenSize = MediaQuery.sizeOf(context);
  //   final widgetHei_ = screenSize.height * .6;
  //   final widgetWid_ = screenSize.width * .5;

  //   showDialog(
  //       context: context,
  //       barrierDismissible: false,
  //       builder: (_) => ChangeNotifierProvider.value(
  //           value: context.read<TermsProvider>(),
  //           child: AlertDialog(
  //             backgroundColor: Colors.white,
  //             contentTextStyle: TextStyle(
  //                 fontSize: 16,
  //                 color: Colors.black,
  //                 fontWeight: FontWeight.w400),
  //             title: AppBar(
  //                 backgroundColor: Colors.white,
  //                 title: const Text('Declaration 聲明',
  //                     style: TextStyle(fontWeight: FontWeight.bold)),
  //                 centerTitle: true,
  //                 automaticallyImplyLeading: false,
  //                 actions: [
  //                   IconButton(
  //                       icon: const Icon(Icons.close),
  //                       color: Colors.black,
  //                       onPressed: () => Navigator.of(context).pop()),
  //                 ]),
  //             content: SizedBox(
  //               width: widgetWid_,
  //               height: widgetHei_,
  //               child: Column(
  //                 crossAxisAlignment: CrossAxisAlignment.start,
  //                 children: [
  //                   Expanded(
  //                     child: SingleChildScrollView(
  //                       child: Container(
  //                         padding: const EdgeInsets.fromLTRB(10, 10, 3, 10),
  //                         decoration: BoxDecoration(
  //                           border: Border.all(
  //                               width: 2,
  //                               color: Colors.blue,
  //                               style: BorderStyle.solid),
  //                         ),
  //                         child: RichText(text: const TextSpan(text: 'HAHAHA')),
  //                       ),
  //                     ),
  //                   ),
  //                   const SizedBox(height: 10),
  //                   Row(
  //                     mainAxisAlignment: MainAxisAlignment.center,
  //                     children: [
  //                       Selector<TermsProvider, bool>(
  //                           selector: (_, provider) =>
  //                               provider.formFieldState?.value ?? false,
  //                           builder: (_, prov, __) {
  //                             return Checkbox(
  //                               value: prov,
  //                               onChanged: (value) {
  //                                 context.read<TermsProvider>().toggle();
  //                                 if (value == true) {
  //                                   Navigator.of(context).pop();
  //                                 }
  //                               },
  //                             );
  //                           }),
  //                       const SizedBox(width: 4),
  //                       const Text("I agree to the above declaration 本人同意以上聲明",
  //                           style: TextStyle(
  //                               fontSize: 14, fontWeight: FontWeight.bold))
  //                     ],
  //                   ),
  //                 ],
  //               ),
  //             ),
  //           )));
  // }

  @override
  Widget build(BuildContext context) {
    return FormField<bool>(
      initialValue: false,
      validator: (value) =>
          value == true ? null : "Please read and accept the terms",
      builder: (formFieldState) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Checkbox(
                  value: formFieldState.value ?? false,
                  checkColor: Colors.white,
                  side: WidgetStateBorderSide.resolveWith(
                    (states) => BorderSide(width: 2, color: Colors.white),
                  ),
                  fillColor: WidgetStateProperty.resolveWith<Color>((states) {
                    return Colors.transparent;
                  }),
                  onChanged: formFieldState.didChange,
                ),
                InkWell(
                  onTap: () {},
                  child: Text.rich(
                    style: customTextStyle(fontSize: 14, opacity: 0.5),
                    TextSpan(
                      style: TextStyle(fontWeight: FontWeight.bold),
                      children: [
                        TextSpan(text: 'Agree to '),
                        TextSpan(
                            text: 'Terms',
                            style:
                                customTextStyle(fontSize: 16, fontWeight: 600)),
                        TextSpan(text: ' & '),
                        TextSpan(
                            text: 'Conditions.',
                            style:
                                customTextStyle(fontSize: 16, fontWeight: 600)),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            // Add this to show validation error
            if (formFieldState.hasError)
              Padding(
                padding: EdgeInsets.only(left: 16.w, top: 0.h),
                child: Text(
                  formFieldState.errorText!,
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.error,
                    fontSize: 12.sp,
                  ),
                ),
              ),
          ],
        );
      },
    );
  }
}

class LoginButton extends StatelessWidget {
  final VoidCallback onPressed;

  const LoginButton({super.key, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: AppColors.white, // Background color
        //  foregroundColor: FamilyTextColor.black, // Text color
        minimumSize:
            Size(double.infinity, 56.h), // Match original height + padding
        padding: EdgeInsets.symmetric(vertical: 18.h), // Original padding
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r), // Original border radius
        ),
        elevation: 0, // Remove default shadow if needed
      ),
      child: Text(
        'Log in',
        style: customTextStyle(
          fontSize: 20,
          fontWeight: 700,
          color: FamilyTextColor.black,
        ),
      ),
    );
  }
}
